import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      //一个路径显示连个组件
      path: '/home',
      components: {
        default: () => import("@/views/Home.vue"),
        footer: () => import("@/components/Footer.vue")
      }
    },
    {
      path: '/login',
      name: "login",
      component: () => import("@/views/Login.vue")
    },
    {
      path: '/address',
      name: "address",
      component: () => import("@/views/Address.vue"),
      /* 添加动态权限控制 */
      meta: { requiresAuth: true }
    },
    {
      path: '/cart',
      name: "cart",
      components: {
        default: () => import("@/views/Cart.vue"),
        footer: () => import("@/components/Footer.vue")
      },
      /* 添加动态权限控制 */
      meta: { requiresAuth: true }
    },
    {
      path: '/center',
      name: "center",
      components: {
        default: () => import("@/views/Center.vue"),
        footer: () => import("@/components/Footer.vue")
      },
      /* 添加动态权限控制 */
      meta: { requiresAuth: true }
    },
    {
      path: '/detail',
      name: "detail",
      component: () => import("@/views/Detail.vue")
    },
    {
      path: '/order',
      name: "order",
      component: () => import("@/views/Order.vue"),
      /* 添加动态权限控制 */
      meta: { requiresAuth: true }
    },
    {
      path: '/register',
      name: "register",
      component: () => import("@/views/Register.vue"),
      children: [
        {
          path: "/register/step1",
          component: () => import("@/views/RegSep1.vue"),
        },
        {
          path: "/register/step2",
          component: () => import("@/views/RegSep2.vue"),
        },
        {
          path: "/register/step3",
          component: () => import("@/views/RegSep3.vue"),
        },
        {
          path: "/register",
          redirect: "/register/step1",
        },
      ]
    },
    {
      path: '/search',
      name: "search",
      component: () => import("@/views/Search.vue")
    },
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import("@/views/NotFound.vue")
    },
  ]
})

/* 全局前置导航守卫实现路由的权限控制 */
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    //获取userid,token =>判断是否存在,如果存在,放行,如果不存在,那么就跳转到登录页面
    if (localStorage.getItem("token") && localStorage.getItem("userid")) {
      //登录过,放行
      next();
    } else {
      //没有登录过,强制跳转登录页面
      next("/login")
    }
  } else {
    next();
  }
})
export default router
